from flask import Blueprint, request, jsonify
from dao.baby_sleep_records_dao import get_baby_sleep_records
from datetime import datetime, timedelta

records_blueprint = Blueprint('records', __name__)


# 根据不同条件获取睡眠记录
@records_blueprint.route('/get/<int:baby_id>/<int:time>', methods=['GET'])
def getRecordsByBabyIdAndTimeScope(baby_id, time):
    end_date = datetime.now()  # 结束日期为当前时间
    start_date = None  # 初始化为 None

    # 根据 time 参数计算开始日期
    if time == 1:
        # 最近24小时
        start_date = end_date - timedelta(hours=24)
    elif time == 3:
        # 最近三天
        start_date = end_date - timedelta(days=3)
    elif time == 7:
        # 最近七天
        start_date = end_date - timedelta(days=7)
    elif time == 30:
        # 最近三十天
        start_date = end_date - timedelta(days=30)
    elif time == 0:
        # 所有记录，从2000年开始
        start_date = datetime(2000, 1, 1)
    else:
        # 无效的 time 参数
        return jsonify({'error': '无效的时间值。它应该是 0, 1, 3, 7 或 30。'}), 400

        # 确保 start_date 不是 None，才进行查询
    if start_date is not None:
        # 格式化 start_date 和 end_date
        formatted_start_date = start_date.strftime('%Y-%m-%d %H:%M:%S')
        formatted_end_date = end_date.strftime('%Y-%m-%d %H:%M:%S')

        # 获取睡眠记录
        sleep_records = get_baby_sleep_records(baby_id, start_date)
        return jsonify({
            'records': sleep_records,
            'start_date': formatted_start_date,
            'end_date': formatted_end_date
        })
    else:
        # 如果没有有效的 time 参数，返回错误
        return jsonify({'error': '时间参数无效。'}), 400


